"""
File:blog_tags.py
Author:Tcyw
Date:2020-03-20
Connect:741047561@qq.com
Description:

"""
from django import template
from django.db.models import Count

from blog.models import Post, Category, Tag

# 最新文章模板标签
# 创建模板库对象
register = template.Library()
# 将函数get_recent_posts添加到模版中
@register.simple_tag
def get_recent_posts(num=5):
    post = Post.objects.all().order_by('-created_time')[:num]
    return post


# 归档模板标签
@register.simple_tag
def archives():
    date = Post.objects.dates('created_time', 'month', order='DESC')
    print(date)
    return date
# 分类模板标签
@register.simple_tag
def get_categories():
    # 别忘了在顶部引入 Category 类
    return Category.objects.all()
# 标签模板标签
@register.simple_tag
def get_tags():
    # 别忘了在顶部引入 Category 类
    return Tag.objects.all()

@register.simple_tag
def get_categories():
    # 记得在顶部引入 count 函数
    # Count 计算分类下的文章数，其接受的参数为需要计数的模型的名称
    return Category.objects.annotate(num_posts=Count('post')).filter(num_posts__gt=0)


